package com.zzusedating.androidapp;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.zzusedating.androidapp.customlayout.TextViewWithClearButton;
import com.zzusedating.androidapp.customlayout.TitleBarLayout;
import com.zzusedating.androidapp.tools.MyApplication;
import com.zzusedating.androidapp.tools.ConstantsTools;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

import static com.zzusedating.androidapp.customlayout.TitleBarLayout.TO_ICON;
import static com.zzusedating.androidapp.customlayout.TitleBarLayout.TO_TEXT;

public class LoginActivity extends BaseActivity {
    private static final int LOGIN_SUCCESS_I = 120;
    private static final int PASSWORD_WRONG_I = 121;
    private static final int USER_NOT_FOUND_I = 122;

    private static final String LOGIN_SUCCESS_ = "登录成功";
    private static final String PASSWORD_WRONG_ = "密码错误";
    private static final String USER_NOT_FOUND_ = "用户不存在";
    private static final String TAG = "LoginActivity";

    private TextViewWithClearButton nameView;
    private TextViewWithClearButton passwordView;

    private Button loginButton;
    private Button regButton;

    private Callback loginCallback;
    private Handler handler;

    private View.OnClickListener regListener;
    private View.OnClickListener loginListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_layout);

        initCallback();
        initListener();

        nameView = findViewById(R.id.Login_UserNameTextView);
        passwordView = findViewById(R.id.Login_Password);
        loginButton = findViewById(R.id.Login_LoginButton);
        regButton = findViewById(R.id.Login_RegisterButton);

        loginButton.setOnClickListener(loginListener);
        regButton.setOnClickListener(regListener);


        TitleBarLayout titleBar = findViewById(R.id.Login_TitleBar);
        titleBar.setClickListenerTo(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this, ForgetPasswordActivity.class));
            }
        }, TO_TEXT);
    }

    public void initListener(){
        regListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
            }
        };
        loginListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = nameView.getText();
                String password = passwordView.getText();

                if (TextUtils.isEmpty(name) || TextUtils.isEmpty(password)){
                    Toast.makeText(LoginActivity.this, "请输入账号和密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                Request request = new Request.Builder()
                        .get()
                        .url(String.format(ConstantsTools.LOGIN, name, password))
                        .build();
                MyApplication.getClient().newCall(request).enqueue(loginCallback);
            }
        };
    }

    public void initCallback(){
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what){
                    case PASSWORD_WRONG_I:
                        Toast.makeText(LoginActivity.this, PASSWORD_WRONG_, Toast.LENGTH_SHORT).show();
                        break;
                    case USER_NOT_FOUND_I:
                        Toast.makeText(LoginActivity.this, USER_NOT_FOUND_, Toast.LENGTH_SHORT).show();
                        break;
                    case LOGIN_SUCCESS_I:
                        Toast.makeText(LoginActivity.this, LOGIN_SUCCESS_, Toast.LENGTH_SHORT).show();
                        MyApplication.setBasicProfile((JSONObject) msg.obj);
                        startActivity(new Intent(LoginActivity.this, MainActivity.class));
                        finish();
                        break;
                    case ConstantsTools.NETWORK_ERROR_I:
                        Toast.makeText(LoginActivity.this, ConstantsTools.NETWORK_ERROR_, Toast.LENGTH_SHORT).show();
                        break;
                }
                return true;
            }
        });
        loginCallback = new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                handler.sendMessage(ConstantsTools.createMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.code() != 200){
                    Log.e(TAG, "onResponse: code: " + response.code());
                    return;
                }
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    if (jsonObject.getInt("status") == 1){
                        handler.sendMessage(ConstantsTools.createMessage(LOGIN_SUCCESS_I, jsonObject.getJSONObject("data")));
                    }
                    else {
                        if (jsonObject.getInt("code") == 4)
                            handler.sendMessage(ConstantsTools.createMessage(PASSWORD_WRONG_I));
                        else if (jsonObject.getInt("code") == 5)
                            handler.sendMessage(ConstantsTools.createMessage(USER_NOT_FOUND_I));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
    }
}
